import json
from datetime import datetime
from app.encrypt.encrypt import simple_encrypt,complex_encrypt

'''
返回给前端的结果类
'''
class Result:
    def __init__(self, code, message, data=None):
        self.code = code  # 状态码，建议0代表失败，1代表成功
        self.message = message # 提示信息
        self.data = data # 返回的数据
        self.timestamp = datetime.now().__str__() # 时间戳

    # 递归转化成字典
    def _convert_to_dict_recursive(self, obj):
        if hasattr(obj, '__dict__'):
            return {key: self._convert_to_dict_recursive(value) for key, value in obj.__dict__.items()}
        elif isinstance(obj, list):
            return [self._convert_to_dict_recursive(item) for item in obj]
        return obj

    def __str__(self):
        result_dict = self.__dict__.copy()
        # 将data字段转换为字典
        result_dict['data'] = self._convert_to_dict_recursive(self.data)
        # 返回加密数据
        return complex_encrypt(json.dumps(result_dict))

    # 成功的返回方法
    @staticmethod
    def success(message=None, data=None):
        return str(Result(1, 'success', data))

    # 失败的返回方法
    @staticmethod
    def fail(message=None, data=None):
        return str(Result(0, message, data))
